using System;
using System.Globalization;
using GammaJul.ReSharper.GammaXaml.Highlightings.CSharp;
using JetBrains.Annotations;
using JetBrains.Application.Progress;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Bulbs;
using JetBrains.ReSharper.Intentions.Extensibility;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.TextControl;
using JetBrains.Util;

namespace GammaJul.ReSharper.GammaXaml.QuickFixes.CSharp {

	/// <summary>
	/// Quick fix that changes a dependency property registration to use its containing type.
	/// </summary>
	[QuickFix]
	public sealed class ChangeOwnerToContainingTypeFix : QuickFixBase {
		private readonly OwnerShouldBeContainingTypeHighlighting _highlighting;

		public override string Text {
			get {
				string typeName = _highlighting.ContainingTypeElement.ShortName;
				return _highlighting.DpField == null
					? String.Format(CultureInfo.CurrentCulture, "Change registration owner type to '{0}'", typeName)
					: String.Format(CultureInfo.CurrentCulture, "Change registered owner type of '{0}' to '{1}'", _highlighting.DpField.ShortName, typeName);
			}
		}

		protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) {
			_highlighting.TypeofExpression.SetTypeName(CSharpElementFactory
				.GetInstance(_highlighting.TypeofExpression.GetPsiModule())
				.CreateTypeUsageNode(TypeFactory.CreateType(_highlighting.ContainingTypeElement)));

			return null;
		}

		public override bool IsAvailable(IUserDataHolder cache) {
			return _highlighting.IsValid();
		}

		public ChangeOwnerToContainingTypeFix([NotNull] OwnerShouldBeContainingTypeHighlighting highlighting) {
			if (highlighting == null)
				throw new ArgumentNullException("highlighting");
			_highlighting = highlighting;
		}
	}
}
